package com.century.sjt.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.R;
import com.century.sjt.entity.noTransactionRecord;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 未结算订单适配器
 */
public class PaynoTransactionRecordAdapter extends BaseAdapter {
    private List<noTransactionRecord> mDataList;
    private LayoutInflater mLayoutInflater;
    private Context context;
    private RequestQueue mQueue;
    private String orderStatus;
    private String pageSize="10";
    private int iCurrPage=1;

    public PaynoTransactionRecordAdapter(List<noTransactionRecord> mDataList, Context context, RequestQueue mQueue){
        this.mQueue=mQueue;
        this.mDataList=mDataList;
        this.context=context;
//        this.type=type;
        mLayoutInflater=LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return mDataList.size();
    }

    @Override
    public Object getItem(int i) {
        return mDataList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int i, View convertView, ViewGroup viewGroup) {

        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            //由于我们只需要将XML转化为View，并不涉及到具体的布局，所以第二个参数通常设置为null
            convertView = mLayoutInflater.inflate(R.layout.sjt_payno_item, null);
            holder.tvPayTime= (TextView) convertView.findViewById(R.id.pay_time);
            holder.tvPayJs= (TextView) convertView.findViewById(R.id.pay_zt);
            holder.tvPayJe= (TextView) convertView.findViewById(R.id.pay_je);
            holder.tvPayTj= (TextView) convertView.findViewById(R.id.pay_tj);
            holder.tvPayId=(TextView) convertView.findViewById(R.id.pay_payid);
            holder.tvButton=(Button)convertView.findViewById(R.id.pay_btn);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        noTransactionRecord transactionRecord=mDataList.get(i);
        holder.tvPayTj.setText(transactionRecord.getOrderMerchant());
        holder.tvPayJe.setText("￥"+transactionRecord.getOrderAmount());
//        holder.tvPayJs.setText(transactionRecord.getOrderPayType());
        holder.tvPayTime.setText(transactionRecord.getOrderTime());
        holder.tvPayId.setText(context.getResources().getString(R.string.text_order_number)+transactionRecord.getOrderNo());
        orderStatus=transactionRecord.getOrderStatus();
//        Log.e("ss",orderStatus);
        /**
         * 订单状态-待结算
         */
//        public static final String ORDER_STATUS_SETTLING = "1";
//        public static final String ORDER_STATUS_SETTLING_CN = "待结算";
//
//        public static final String ORDER_STATUS_REVOCATION_APPLY = "4";
//        public static final String ORDER_STATUS_REVOCATION_APPLY_CN = "退款申请";


        switch (orderStatus) {
            case "0":
//                holder.tvPayJs.setVisibility(View.VISIBLE);
//                holder.tvButton.setVisibility(View.GONE);
                break;
            case "1":
                holder.tvPayJs.setVisibility(View.GONE);
                holder.tvButton.setVisibility(View.VISIBLE);
                final String OrderNo = mDataList.get(i).getOrderNo();
                holder.tvButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                            refund(OrderNo);
                        showAppayRes(OrderNo,i);
                            }
                     });
                break;
            case "2":
//                holder.tvPayJs.setVisibility(View.GONE);
//                holder.tvButton.setVisibility(View.VISIBLE);
//                holder.tvButton.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        refund(OrderNo);
//                    }
//                });
                break;
            case "3":
                break;
            case "4":
                holder.tvPayJs.setVisibility(View.VISIBLE);
                holder.tvButton.setVisibility(View.GONE);
                break;
            default:
//                TipUtil.showToast("粗错啦！", context, 1);
        }
//        if (holder.tvPayTj.getText().equals("充值")){
//            holder.tvPayJs.setVisibility(View.GONE);
//            holder.tvButton.setVisibility(View.VISIBLE);
//        }
//
//        holder.tvButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Log.e("main","点击");
//            }
//        });
//        //交易订单情况
//
//        if (holder.tvPayJs.getText().toString().equals("支付成功")){
//            holder.tvPayJs.setTextColor(context.getResources().getColor(R.color.pay_success));
//        }else if (holder.tvPayJs.getText().toString().equals("支付失败")){
//            holder.tvPayJs.setTextColor(context.getResources().getColor(R.color.pay_error));
//        }else {
//            holder.tvPayJs.setTextColor(context.getResources().getColor(R.color.pay_dismiss));
//        }
        return convertView;
    }

    // ViewHolder用于缓存控件
    static class ViewHolder {
        public TextView tvPayTj;                //交易类型
        public TextView tvPayJs;                //交易状态
        public TextView tvPayJe;                //交易金额
        public TextView tvPayTime;             //交易时间
        public TextView tvPayId;               //交易单号
        public Button tvButton;                 //申请退款按钮
    }



    //申请退款
    private void refund(final String orderNo,final int position){
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting),mContext);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.Refund, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.log("申请退款", response, 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
//                        mDataList.remove(position);
                        getRecords();
                        TipUtil.showToast(context.getResources().getString(R.string.error_in_refund_success), context, 1);
                    } else {//失败
                        TipUtil.showToast(message, context, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(context.getResources().getString(R.string.error_service), context, 1);
                }
                notifyDataSetChanged();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(context.getResources().getString(R.string.error_network), context, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences =context. getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("orderNo",orderNo);
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences =context. getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }
    //获取未结算订单
    private void getRecords(){
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting),mContext);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.UserNoSettleOrders, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.log("未结算订单", response, 1);
//                    loadMore.setText("加载更多");
//                    loadMore.setEnabled(true);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        JSONArray data = res.getJSONArray("data");
                        mDataList.clear();
                        for(int i=0;i<data.length();i++){
                            JSONObject dataObject=data.getJSONObject(i);
                            noTransactionRecord transactionRecord=new noTransactionRecord();
                            transactionRecord.setOrderStatus(dataObject.getString("orderStatus"));
                            transactionRecord.setOrderTime(dataObject.getString("orderTime"));
                            transactionRecord.setOrderAmount(dataObject.getString("orderAmount"));
                            transactionRecord.setOrderUser(dataObject.getString("orderUser"));
                            transactionRecord.setUserMobile(dataObject.getString("userMobile"));
                            transactionRecord.setOrderMerchant(dataObject.getString("orderMerchant"));
                            transactionRecord.setOrderNo(dataObject.getString("orderNo"));
                            transactionRecord.setOrderPayType(dataObject.getString("orderPayType"));
                            transactionRecord.setPayCardNo(dataObject.getString("payCardNo"));
                            transactionRecord.setBankCode(dataObject.getString("bankCode"));
                            mDataList.add(transactionRecord);
                        }

                    } else {//失败
                        TipUtil.showToast(message, context, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(context.getString(R.string.error_service), context, 1);
                }
                TipUtil.closeProgressDialog();
                notifyDataSetChanged();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(context.getString(R.string.error_network), context, 1);
                TipUtil.closeProgressDialog();

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences =context. getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("paging.pageSize", Constant.PAGESIZE+"");
                map.put("paging.currentPage",String.valueOf(iCurrPage));
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences =context. getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }

    public void showAppayRes(final String orderNo,final int position) {
        //询问是否取消
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(context.getResources().getString(R.string.text_prompt));
        builder.setMessage(context.getResources().getString(R.string.error_in_refund));
        builder.setPositiveButton(context.getResources().getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                refund(orderNo,position);
            }
        });
        builder.setNegativeButton(context.getResources().getString(R.string.btn_no), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setCancelable(false);
        builder.create().show();
    }

}
